package com.selfdiscipline.ui.screens.timer

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.selfdiscipline.domain.repository.TimerRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import javax.inject.Inject
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
import kotlin.time.Duration.Companion.seconds
import kotlin.time.Duration.Companion.milliseconds

/**
 * 时间单位扩展
 */
private val Long.milliseconds: Duration
    get() = Duration.parse("${this}ms")

/**
 * 计时器UI状态
 */
data class TimerUiState(
    val timerMode: TimerMode = TimerMode.FOCUS,
    val targetTime: Duration = TimerMode.FOCUS.defaultDuration,
    val remainingTime: Duration = TimerMode.FOCUS.defaultDuration,
    val progress: Float = 1f,
    val elapsedTime: Duration = Duration.ZERO,
    val isRunning: Boolean = false,
    val completedPomodoros: Int = 0
)

@HiltViewModel
class TimerViewModel @Inject constructor(
    private val timerRepository: TimerRepository
) : ViewModel() {
    
    private val _uiState = MutableStateFlow(TimerUiState())
    val uiState: StateFlow<TimerUiState> = _uiState.asStateFlow()
    
    private var timerJob: Job? = null
    
    init {
        setTimerMode(TimerMode.FOCUS)
    }
    
    fun setTimerMode(mode: TimerMode) {
        pauseTimer()
        
        val targetTime = when (mode) {
            TimerMode.FOCUS -> 25.minutes
            TimerMode.SHORT_BREAK -> 5.minutes
            TimerMode.LONG_BREAK -> 15.minutes
        }
        
        _uiState.update { 
            it.copy(
                timerMode = mode,
                targetTime = targetTime,
                remainingTime = targetTime,
                progress = 1f,
                elapsedTime = Duration.ZERO
            )
        }
    }
    
    fun startTimer() {
        if (timerJob != null) return
        
        timerJob = viewModelScope.launch {
            val startTime = System.currentTimeMillis()
            val initialRemaining = _uiState.value.remainingTime
            
            _uiState.update { it.copy(isRunning = true) }
            
            while (_uiState.value.remainingTime > Duration.ZERO) {
                delay(100) // 更新频率为100毫秒
                
                val elapsed = (System.currentTimeMillis() - startTime).milliseconds
                val remaining = (initialRemaining - elapsed).coerceAtLeast(Duration.ZERO)
                val progress = if (initialRemaining.inWholeMilliseconds > 0) {
                    remaining.inWholeMilliseconds.toFloat() / initialRemaining.inWholeMilliseconds
                } else 0f
                
                _uiState.update { 
                    it.copy(
                        remainingTime = remaining,
                        progress = progress,
                        elapsedTime = it.elapsedTime + 100.milliseconds
                    )
                }
                
                if (remaining <= Duration.ZERO) {
                    onTimerComplete()
                    break
                }
            }
        }
    }
    
    fun pauseTimer() {
        timerJob?.cancel()
        timerJob = null
        _uiState.update { it.copy(isRunning = false) }
    }
    
    fun resetTimer() {
        pauseTimer()
        _uiState.update { 
            it.copy(
                remainingTime = it.targetTime,
                progress = 1f,
                elapsedTime = Duration.ZERO
            )
        }
    }
    
    fun stopTimer() {
        pauseTimer()
        _uiState.update { it.copy(elapsedTime = Duration.ZERO) }
    }
    
    private fun onTimerComplete() {
        pauseTimer()
        
        when (_uiState.value.timerMode) {
            TimerMode.FOCUS -> {
                _uiState.update { 
                    it.copy(
                        completedPomodoros = it.completedPomodoros + 1
                    )
                }
                
                // 完成4个番茄钟后进入长休息，否则进入短休息
                if (_uiState.value.completedPomodoros % 4 == 0) {
                    setTimerMode(TimerMode.LONG_BREAK)
                } else {
                    setTimerMode(TimerMode.SHORT_BREAK)
                }
            }
            TimerMode.SHORT_BREAK, TimerMode.LONG_BREAK -> {
                setTimerMode(TimerMode.FOCUS)
            }
        }
    }
    
    fun saveTimeRecord(title: String, category: String) {
        viewModelScope.launch {
            timerRepository.saveTimeRecord(
                title = title,
                category = category,
                duration = _uiState.value.elapsedTime
            )
            
            // 重置计时器
            resetTimer()
        }
    }
    
    override fun onCleared() {
        super.onCleared()
        pauseTimer()
    }
} 